<template>
<div class="flex items-center justify-center pt-20 flex-col">
  <div class="text-4xl text-neutral-500">儿童拼音练习</div>
  <div class="pt-1">
    <div>完成量：{{correctCount}}/{{correctCount+wrongCount}} </div>
    <div>正确率：{{(correctCount+wrongCount) !=0 ? Math.round(correctCount/(correctCount+wrongCount)*100):0}} %</div>
  </div>
  <div class="text-8xl pt-10 text-lime-800">{{currentPinyin}}</div>

  <div class="flex flex-col justify-center pt-10">
    <button class="bg-sky-500 hover:bg-sky-700 m-2 rounded-lg p-4 text-2xl text-blue-50" 
    v-for="(category, index) in categories" :key="index"
    @click="checkAnswer(category)"
    >{{ category }}</button>
  </div>
  <div class="pt-10" :class="feedbackClass">
    {{feedback}}
  </div>
</div>
</template>

<script setup lang="ts">

import { ref, onMounted } from 'vue'
import { initials, finals, wholeSyllables, allPinyin } from './pinyinData'

const currentPinyin = ref('')
const categories = ['声母', '韵母', '整体认读']
const feedback = ref('')
const feedbackClass = ref('')
const showCorrectAnswer = ref(false)
const correctCategory = ref('')
const correctCount = ref(0)
const wrongCount = ref(0)

// 获取随机拼音
const getRandomPinyin = () => {
  const randomIndex = Math.floor(Math.random() * allPinyin.length)
  // 确保获取到的拼音不为 undefined，若为 undefined 则使用空字符串作为默认值
  currentPinyin.value = allPinyin[randomIndex] ?? ''
}

// 判断拼音所属分类
const getCategory = (pinyin: string) => {
  if (initials.includes(pinyin)) return '声母'
  if (finals.includes(pinyin)) return '韵母'
  if (wholeSyllables.includes(pinyin)) return '整体认读'
  return ''
}

// 检查答案
const checkAnswer = (selectedCategory: string) => {
  const realCategory = getCategory(currentPinyin.value)
  correctCategory.value = realCategory
  let tt:number = 500;
  if (selectedCategory === realCategory) {
    feedback.value = '太棒啦，回答正确！继续加油哦！'
    feedbackClass.value = 'text-green-500'
    correctCount.value++
    showCorrectAnswer.value = false
  } else {
    feedback.value = '哎呀，答错啦！正确答案应该是：'+realCategory
    feedbackClass.value = 'text-red-500'
    wrongCount.value++
    showCorrectAnswer.value = true
    tt = 2000
  }
  // 存储练习记录
  // localStorage.setItem('pinyinPractice', JSON.stringify({ correct: correctCount.value, wrong: wrongCount.value }))
  setTimeout(() => {
    getRandomPinyin()
    feedback.value = ''
  }, tt)
}

onMounted(() => {
  getRandomPinyin()
  // 读取练习记录
  // const record = localStorage.getItem('pinyinPractice')
  // if (record) {
  //   const { correct, wrong } = JSON.parse(record)
  //   correctCount.value = correct
  //   wrongCount.value = wrong
  // }
})
</script>